import axios from 'axios'
import env from './env.js'
import { showToast,showLoadingToast,closeToast } from 'vant';
import router from './router'
const instance = axios.create({
    baseURL: env.baseUrl,
    timeout: 10000
})
instance.interceptors.request.use((config) => {
    if (config.headers && !config.headers.noLoading) {
        showLoadingToast({
            message: 'Loading',
            forbidClick: true,
            overlay: true,
            duration: 10000
        })
    }
    config.headers['token'] = localStorage.getItem('token')
    return config
})
instance.interceptors.response.use((response) => {
    closeToast()
    if (response.status == 200) {
        if (response.data.code == 1) {
            return response.data
        } else {
            showToast(response.data.msg);
            return response.data
        }
    } else {
        showToast(response.statusText);
    }
},error => {
    closeToast()
    if (error.response.status == 301) {
        window.location.replace(error.response.data.data)
        return;
    }
    if (error && error.response && error.response.status == 401) {
        showToast('Login failed, please log in again')
        localStorage.removeItem('token')
        router.push('login')
    }
    if (error.code === 'ECONNABORTED') {
        showToast('No response, please try again later')
    }
})
export default instance